# pip install httpx

import aiohttp
import httpx


async def aio_httpx_request(method, url, data=None, params=None, json=None,
                            headers=None, verify=False, proxies=None, timeout=None,
                            **kwargs):
    '''
    :param method:请求方式，字符串类型
    :param url: 字符串类型
    :param data:字典类型
    :param json:字典类型
    :param headers:字典类型
    :param verify:是否验证证书
    :param proxies:代理
    :param timeout:超时时间
    :param params: 类似于key,value的格式
    :return:response对象,取返回体方式：response.text
    '''

    # # 10.60.164.32 可根据配置文件中的配置进行修改，此处为了方便直接写死
    # proxies = {
    #     "http://": f"http://10.60.164.32:80",
    #     "https://": f"https://10.60.164.32:443",
    # }
    async with httpx.AsyncClient(proxies=proxies, verify=verify, timeout=timeout) as client:
        response = await client.request(
            method=method, url=url,
            data=data, params=params,
            json=json, headers=headers,
            **kwargs
        )
        return response


async def get(url: str, data=None, **kwargs):
    """
    发送GET请求

    :param url:
    :param data:
    :return:
    """
    payload = {}
    if isinstance(data, dict):
        payload.update(data)
    else:
        payload = data
    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=payload, **kwargs) as response:
            result = await response.text()
            if isinstance(result, bytes):
                return response.status, result.decode('utf-8')
            return response.status, result

async def post(url: str, data=None, json=None, **kwargs):
    """
    发送POST请求

    :param url: 请求URL
    :param data: 请求附带数据
    :param json: 请求附带json数据
    :param kwargs: 参数列表
    :return:
    """
    if not data and not json:
        raise ValueError('data and json parameters can not be used at the same time.')
    payload = {}
    if isinstance(data, dict):
        payload.update(data)
    else:
        payload = data
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=payload, json=json, **kwargs) as response:
            result = await response.read()
            if isinstance(result, bytes):
                return response.status, result.decode('utf-8')
            return response.status, result



async def demo():
    url = 'https://www.baidu.com'
    response = await aio_httpx_request('GET', url)
    print(response.text)


if __name__ == '__main__':
    import asyncio

    loop = asyncio.get_event_loop()
    loop.run_until_complete(demo())
